package com.duan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.duan.exception.SpringSecurityException;
import com.duan.mapper.SysMenuMapper;
import com.duan.mapper.SysUserMapper;
import com.duan.pojo.LoginUser;
import com.duan.pojo.SysUser;
import com.duan.utils.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author db
 * @version 1.0
 * @description UserDetailsServiceImpl
 * @since 2024/9/22
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName,username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser == null){
            throw new SpringSecurityException(AppHttpCodeEnum.LOGIN_ERROR.getCode(),AppHttpCodeEnum.LOGIN_ERROR.getMsg());
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> perms = sysMenuMapper.selectPermsByUserId(sysUser.getId());
        //封装成UserDetails对象返回
        return new LoginUser(sysUser,perms);
    }
}
